# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json
import sqlite3

# class Top100MoviesPipeline(object):
#     # 定义构造器，初始化要写入的文件
#     def __init__(self):
#         self.json_file = open("top100movies.json", "wb+")
#         self.json_file.write('[\n'.encode("utf-8"))
#     # 重写close_spider回调方法，用于关闭文件
#     def close_spider(self, spider):
#         print('----------关闭文件-----------')
#         # 后退2个字符，也就是去掉最后一条记录之后的换行符和逗号
#         self.json_file.seek(-2, 1)
#         self.json_file.write('\n]'.encode("utf-8"))
#         self.json_file.close()
#     def process_item(self, item, spider):
#         # 将item转换成JSON字符串
#         text = json.dumps(dict(item), ensure_ascii=False) + ",\n"
#         # 写入JSON字符串
#         self.json_file.write(text.encode("utf-8"))


# class Top100MoviesPipeline(object):
#     def process_item(self, item, spider):
#         print("movie_name:" , item['movie_name'])
#         print("movie_director:" , item['movie_director'])
#         print("movie_point:", item['movie_point'])


class Top100MoviesPipeline(object):
    def __init__(self):
        self.conn = sqlite3.connect('top100movies.db')
        self.c = self.conn.cursor()
        self.c.execute('''create table if not exists top100movies(
                _id integer primary key  autoincrement,
                movie_name,
                movie_director,
                movie_point
            )
        ''')

    def process_item(self, item, spider):
        self.c.execute('insert into top100movies values (null,?,?,?)',
                       (item['movie_name'], item['movie_director'], item['movie_point']))
        self.conn.commit()

    def close_spider(self,spider):
        self.c.close()
        self.conn.close()
